<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button
        v-permission="['POST /admin/category/create']"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
        >{{ $t("app.button.create") }}</el-button
      >
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      ref="categoryTable"
      :element-loading-text="$t('app.message.list_loading')"
      :header-cell-style="{
        background: 'rgba(239, 241, 244, 0.2)',
        color: '#333333',
      }"
      row-key="id"
      border
      fit
    >
      <el-table-column
        align="center"
        width="50"
        label="排序"
        class-name="sort-column"
      >
        <template>
          <i class="el-icon-rank"></i>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('mall_category.table.id')"
        prop="id"
      />

      <el-table-column
        align="center"
        :label="$t('mall_category.table.name')"
        prop="name"
      />

      <el-table-column
        align="center"
        :label="$t('mall_category.table.keywords')"
        prop="keywords"
      />

      <el-table-column align="center" label="状态" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            :active-value="true"
            :inactive-value="false"
            @change="handleStatusChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('mall_category.table.actions')"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['POST /admin/category/update']"
            type="text"
            @click="handleUpdate(scope.row)"
            >{{ $t("app.button.edit") }}</el-button
          >
          <el-button
            v-permission="['POST /admin/category/delete']"
            type="text"
            style="color: red"
            @click="handleDelete(scope.row)"
            >{{ $t("app.button.delete") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog
      width="60%"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-width="100px"
      >
        <el-form-item :label="$t('mall_category.form.name')" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-switch
            v-model="dataForm.enabled"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        <el-form-item
          :label="$t('mall_category.form.keywords')"
          prop="keywords"
        >
          <el-input v-model="dataForm.keywords" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("app.button.cancel")
        }}</el-button>
        <el-button
          :loading="confirmLoading"
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
          >{{ $t("app.button.confirm") }}</el-button
        >
        <el-button
          :loading="confirmLoading"
          v-else
          type="primary"
          @click="updateData"
          >{{ $t("app.button.confirm") }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listCategory,
  listCatL1,
  createCategory,
  updateCategory,
  deleteCategory,
  updateCategorySort,
} from "@/api/category";
import { uploadPath } from "@/api/storage";
import { getToken } from "@/utils/auth";
import { thumbnail, toPreview } from "@/utils/index";
import Sortable from "sortablejs";

export default {
  name: "Category",
  data() {
    return {
      thumbnail,
      toPreview,
      uploadPath,
      list: [],
      listLoading: true,
      catL1: {},
      dataForm: {
        id: undefined,
        name: "",
        keywords: "",
        level: "L1",
        pid: 0,
        desc: "",
        iconUrl: "",
        picUrl: "",
        sortOrder: 0,
        enabled: true,
      },
      dialogFormVisible: false,
      confirmLoading: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rules: {
        name: [{ required: true, message: "类目名不能为空", trigger: "blur" }],
      },
      oldList: [],
    };
  },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
  },
  created() {
    this.getList();
  },

  mounted() {
    this.initSort();
  },

  methods: {
    getList() {
      this.listLoading = true;
      listCategory()
        .then((response) => {
          this.list = response.data.data.list;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.listLoading = false;
        });
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: "",
        keywords: "",
        level: "L1",
        pid: 0,
        desc: "",
        iconUrl: "",
        picUrl: "",
        sortOrder: 0,
        enabled: true,
      };
    },
    onLevelChange: function (value) {
      if (value === "L1") {
        this.dataForm.pid = 0;
      }
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    uploadIconUrl: function (response) {
      this.dataForm.iconUrl = response.data.url;
    },
    uploadPicUrl: function (response) {
      this.dataForm.picUrl = response.data.url;
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          createCategory(this.dataForm)
            .then((response) => {
              this.getList();
              this.dialogFormVisible = false;
              this.$message.success({
                title: "成功",
                message: "创建成功",
              });
              this.confirmLoading = false;
            })
            .catch((response) => {
              this.$message.error({
                title: "失败",
                message: response.data.errmsg,
              });
              this.confirmLoading = false;
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          updateCategory(this.dataForm)
            .then(() => {
              this.getList();
              this.dialogFormVisible = false;
              this.$message.success({
                title: "成功",
                message: "更新成功",
              });
              this.confirmLoading = false;
            })
            .catch((response) => {
              this.$message.error({
                title: "失败",
                message: response.data.errmsg,
              });
              this.confirmLoading = false;
            });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("数据删除后不可恢复，是否确认删除此条数据？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        deleteCategory(row)
          .then((response) => {
            this.getList();
            this.$message.success({
              title: "成功",
              message: "删除成功",
            });
          })
          .catch((response) => {
            this.$message.error({
              title: "失败",
              message: response.data.errmsg,
            });
          });
      });
    },
    handleStatusChange(row) {
      this.confirmLoading = true;
      updateCategory({
        ...row,
        enabled: row.enabled,
      })
        .then((response) => {
          this.$message.success("状态更新成功");
          this.confirmLoading = false;
        })
        .catch(() => {
          row.enabled = !row.enabled; // 失败时恢复状态
          this.confirmLoading = false;
        });
    },

    // 拖拽排序相关方法
    initSort() {
      const el = this.$refs.categoryTable.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      this.oldList = [...this.list];

      if (Sortable.get(el)) {
        Sortable.get(el).destroy();
      }

      Sortable.create(el, {
        ghostClass: "sortable-ghost",
        handle: ".sort-column",
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0];
          this.list.splice(evt.newIndex, 0, targetRow);
          this.saveSort();
        },
      });
    },

    saveSort() {
      const newOrder = this.list.map((item, index) => {
        return {
          id: item.id,
          sortOrder: index,
        };
      });

      updateCategorySort(newOrder)
        .then((response) => {
          this.$message({
            message: "排序保存成功",
            type: "success",
          });
          this.getList();
        })
        .catch((error) => {
          this.$message.error({
            message: "排序保存失败，请重试",
          });
          // 如果保存失败，恢复原始顺序
          this.list = [...this.oldList];
        });
    },
  },
};
</script>

<style scoped>
.filter-item {
  margin-left: 100px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

/* 排序样式 */
.sort-column i {
  color: #909399;
  font-size: 18px;
  position: relative;
  z-index: 1;
}

.sort-column:hover i {
  color: #409eff;
  cursor: move;
}

.sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #42b983 !important;
}
</style>
